package ro.myApp.client.helpers;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;

import javax.imageio.ImageIO;

import org.jpedal.PdfDecoder;

import com.lowagie.text.pdf.PdfReader;

public class PDFUtils implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7673008873633167702L;

	private static final int preScale=3;
	public static byte[] blobPdfToPageImage(byte[] pdf, int page, int zoom)
			throws Exception {
		
		System.setProperty("org.jpedal.jai", "true");
		System.setProperty("org.jpedal.hires", "true");
		
		if (pdf != null) {
			PdfDecoder decode_pdf = new PdfDecoder();
			decode_pdf.openPdfArray(pdf);
			BufferedImage image;
			decode_pdf.useHiResScreenDisplay(true);
			
			if (page >= 0) {
				decode_pdf.setPageParameters(preScale, page + 1);
				decode_pdf.getDPIFactory().adjustScaling(preScale);
				image = decode_pdf.getPageAsImage(page + 1);
			} else {
				decode_pdf.setPageParameters(preScale, 1);
				decode_pdf.getDPIFactory().adjustScaling(preScale);
				decode_pdf.decodePage(1);
				image = decode_pdf.getPageAsImage(1);
			}
			
			int width = (int) ((image.getWidth() / preScale) * zoom / 100);
			int height = (int) ((image.getHeight() / preScale) * zoom / 100);
			
			Image scaled = image.getScaledInstance(width, height,
					Image.SCALE_SMOOTH);
			image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			image.createGraphics().drawImage(scaled, 0, 0, null);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(image, "jpeg", baos);
			return baos.toByteArray();
		} else
			return null;
	}

	public static int getNumberOfPages(byte[] pdf) {
		try {
			PdfReader reader = new PdfReader(pdf);
			return reader.getNumberOfPages();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
}
